package com.example.studyonlineapplication.fragments;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.studyonlineapplication.R;
import com.example.studyonlineapplication.domain.po.Result;
import com.example.studyonlineapplication.domain.po.User;
import com.example.studyonlineapplication.utils.MyToast;
import com.example.studyonlineapplication.utils.NoteViewPagerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaredrummler.materialspinner.MaterialSpinner;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NoteFragment extends Fragment {
    TabLayout tabLayout;
    ViewPager2 viewPager;
    ImageButton searchButton,addButton,reflushBtn;
    MaterialSpinner spinner ;
    EditText contextEt,searchEt;
    Button cancelBtn,sureBtn;
    CardView addInfoDialog;
    OkHttpClient client = new OkHttpClient();
    Gson gson = new Gson();
    HttpUrl url;
    Request request;
    Result<List<String>> data;
    NoteViewPagerAdapter adapter;

    View view; @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.note_page,container,false);
    }


    public void reflush(String data, boolean isClear){
        if (data==""){
            adapter = new NoteViewPagerAdapter(requireActivity());
        }
        else {
            adapter = new NoteViewPagerAdapter(requireActivity(),data);
        }
        viewPager.setAdapter(adapter);
        if (isClear){
            searchEt.setText("");
        }
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.view = view;
        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.viewPage);
        searchButton = view.findViewById(R.id.searchButton);
        addButton = view.findViewById(R.id.addButton);
        spinner = view.findViewById(R.id.kindSp);
        contextEt = view.findViewById(R.id.contextEt);
        cancelBtn = view.findViewById(R.id.cancelBtn);
        sureBtn = view.findViewById(R.id.sureBtn);
        addInfoDialog = view.findViewById(R.id.addInfoDialog);
        searchEt = view.findViewById(R.id.searchEt);
        reflushBtn = view.findViewById(R.id.reflushBtn);

        reflush("",false);

        new TabLayoutMediator(tabLayout, viewPager,
                (tab, position) -> {
                    if(position==0){
                        tab.setText("今天");
                    }else {
                        tab.setText("全部");
                    }
                }
        ).attach();


        url = HttpUrl.parse("http://10.0.2.2:8080/course/getCourseName")
                .newBuilder()
                .build();
        request = new Request.Builder()
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback(){
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                System.out.println(json+"成功");
                Type resultType = new TypeToken<Result<List<String>>>() {}.getType();
                data = gson.fromJson(json, resultType);
                getActivity().runOnUiThread(()->{
//                    System.out.println(data.getData());
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, data.getData().toArray(new String[0]));
                    spinner.setAdapter(adapter);
                });
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("获取失败");
            }
        });


        reflushBtn.setOnClickListener(v->{
            reflush("",true);
        });
        addButton.setOnClickListener(v->{
            if (addInfoDialog.getVisibility()==View.GONE){
                addInfoDialog.setVisibility(View.VISIBLE);
            }else {
                addInfoDialog.setVisibility(View.GONE);
            }
        });

        searchButton.setOnClickListener(v->{
            reflush(searchEt.getText().toString(),false);
        });

        cancelBtn.setOnClickListener(v->{
            addInfoDialog.setVisibility(View.GONE);
        });

        sureBtn.setOnClickListener(v->{
            SharedPreferences sp = getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
            User user = gson.fromJson(sp.getString("user",""), User.class);
            RequestBody body = new FormBody.Builder()
                    .add("courseName", spinner.getItems().get(spinner.getSelectedIndex()).toString())
                    .add("userId", String.valueOf(user.getId()))
                    .add("noteText",contextEt.getText().toString())
                    .build();
            request = new Request.Builder()
                    .url("http://10.0.2.2:8080/note/addNote")
                    .post(body)
                    .build();
            client.newCall(request).enqueue(new Callback(){

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    String json = response.body().string();
                    System.out.println(json);
                    Result<String> data = gson.fromJson(json,Result.class);
                    getActivity().runOnUiThread(()-> {
                        if (data.getCode()==1){
                            MyToast.message("添加失败",getContext());
                        }
                        else {
                            MyToast.message("添加成功",getContext());

                            addInfoDialog.setVisibility(View.GONE);
                            spinner.setSelectedIndex(0);
                            contextEt.setText("");
                            //刷新
                            reflush("",true);
                        }
                    });
                }

                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    getActivity().runOnUiThread(()-> {
                        MyToast.message("添加失败",getContext());
                    });
                }
            });
        });
    }
}
